#pragma once

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <cstring>
#include "Log.hpp"

class Sock
{
private:
    const static int backlog = 20;

public:
    Sock() {}

    // 返回值是创建的套接字
    int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0)
        {
            logMessage(FATAL, "Create Socket Error! Errno:%d Strerror:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "Create Socket Success! Socket:%d", sock);
        return sock;
    }

    // 绑定端口号
    void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = inet_addr(ip.c_str());
        if (bind(sock, (struct sockaddr *)&local, sizeof local) < 0)
        {
            logMessage(FATAL, "Bind Error! Errno:%d Strerror:%s", errno, strerror(errno));
            exit(3);
        }
    }

    // 将套接字设置为监听套接字
    void Listen(int listenSock)
    {
        if (listen(listenSock, backlog) < 0)
        {
            logMessage(FATAL, "Listen Error! Errno:%d Strerror:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "Init Server Success!");
    }

    // 接收链接,返回值是为该连接服务的套接字
    // ip和port是输出型参数,返回客户端的ip和port
    int Accept(int listenSock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int serviceSock = accept(listenSock, (struct sockaddr *)&src, &len);
        if (serviceSock < 0)
        {
            logMessage(FATAL, "Accept Error! Errno:%d Strerror:%s", errno, strerror(errno));
            return -1;
        }
        if (ip)
            *ip = inet_ntoa(src.sin_addr);
        if (port)
            *port = ntohs(src.sin_port);
        return serviceSock;
    }

    // 发起连接
    bool Connet(int sock, const std::string &serverIP, const int16_t &serverPort)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET;
        server.sin_port = htons(serverPort);
        inet_pton(AF_INET, serverIP.c_str(), &server.sin_addr);

        if (connect(sock, (struct sockaddr *)&server, sizeof server) == 0)
            return true;
        else
            return false;
    }

    ~Sock() {}
};